import secret from './secret';

/**
 * const token = secret.encrypt('123456'); //加密
   secret.decrypt(token); //解密
 */

/**
// 设置cookie
setCookie: function(c_name,value,expiremMinutes){
   var exdate = new Date();
   exdate.setTime(exdate.getTime() + expiremMinutes * 60 * 1000);
   document.cookie= c_name + "=" + escape(value)+((expiremMinutes==null) ? "" : ";expires="+exdate.toGMTString());
},
 
// 读取cookie
getCookie: function(c_name){
   if (document.cookie.length>0)
   {
       var c_start=document.cookie.indexOf(c_name + "=");
       if (c_start!=-1)
       { 
       c_start=c_start + c_name.length+1;
       var c_end=document.cookie.indexOf(";",c_start);
       if (c_end==-1) 
           c_end = document.cookie.length
           return unescape(document.cookie.substring(c_start, c_end))
       }
   }
   return ""   
},
 
// 删除cookie
delCookie: function(c_name){
   var exp = new Date();
   exp.setTime(exp.getTime() - 1);
   var cval = this.getCookie(c_name);
   if(cval!=null){
       document.cookie = c_name + "=" + cval + ";expires=" + exp.toGMTString();
   }
}

 */



/**
 * 设置cookie
 * @param {*} c_name  cookie的key
 * @param {*} value  cookie的value格式为：用户名&密码
 */
export function setCookie(c_name, value) {
    let index = value.indexOf("&");
    if (index != -1) {
        let userName = value.substring(0, index);
        let passWord = value.substring(index + 1);
        // 密码加密
        let newPassWord = secret.encrypt(passWord);
        // 放入cookie
        document.cookie = c_name + "=" + (userName + "&" + newPassWord);
    }
}

/**
 * 获取cookie的值
 * @param {*} c_name  cookie的key
 * 返回的cookie是：用户名&密码
 */
export function getCookie(c_name) {
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            var c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1){
                c_end = document.cookie.length
            }
            let value = document.cookie.substring(c_start, c_end);
            let index = value.indexOf("&");
            if(index != -1){
                let userName = value.substring(0, index);
                let passWord = value.substring(index + 1);
                // 解密
                let realPassWord = secret.decrypt(passWord);
                return (userName + "&" + realPassWord );
            }
            return "" 
        }
    }
    return ""
}

/**
 * 删除cookie
 * @param {*} c_name  cookie的key
 */
export function delCookie(c_name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    document.cookie= c_name + "='';expires="+exp.toGMTString();
}


export default {
    setCookie,
    getCookie,
    delCookie
};
